<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="72px" class="queryForms">
			<el-form-item label="记录编号" prop="recordNumber">
				<el-input v-model="queryParams.recordNumber" placeholder="请输入记录编号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="申请单编号" prop="serialNumber" label-width="90px">
				<el-input v-model="queryParams.serialNumber" placeholder="请输入申请单编号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="申请人" prop="proposerName">
				<el-input v-model="queryParams.proposerName" placeholder="请输入申请人" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="送检时间" prop="inspectTime">
				<el-date-picker v-model="queryParams.inspectTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期"> </el-date-picker>
			</el-form-item>
			<el-form-item label="产品名称" prop="deviceName">
				<el-input v-model="queryParams.deviceName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item label="型号/图号" prop="partNumber" label-width="90px">
				<el-input v-model="queryParams.partNumber" placeholder="请输入型号/图号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleDown" v-hasPermi="['synthesize:sentrancelist:issue']">下发</el-button>
			</el-col>
			<right-toolbar @changeTableData="changeTableData" menuNames="entrancelist58" :showSearch.sync="showSearch" @queryTable="handleQuery" :columns.sync="columns" perm="synthesize:store:entrancelist:index"></right-toolbar>
		</el-row>
		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''" class="informationTab" ref="eleTab">
			<!-- lazy :load="loadListDes" -->
      <el-table :row-class-name="row_class_name" @mousedown.native="mousedownTable" @row-click="row_click" @cell-mouse-enter="cell_mouse_enter" @cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable" @mouseleave.native="mouseupTable" ref="table" v-loading="loading" :data="EntrancelistList" @selection-change="handleSelectionChange" row-key="id"  :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"  border height="100%">
				<el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="55" >
           <template slot-scope="scope">
              <div>{{scope.row.sort}}</div>
           </template>
        </el-table-column>
				<el-table-column label="记录编号" prop="recordNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="申请单编号" prop="serialNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="申请人" prop="proposerName" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="供方" prop="supplier" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="送检时间" prop="inspectTime" min-width="150" :show-overflow-tooltip="true" v-if="columns[4].visible" />
				<el-table-column label="产品名称" prop="deviceName" min-width="150" :show-overflow-tooltip="true" v-if="columns[5].visible" />
				<el-table-column label="型号/图号" prop="partNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[6].visible" />
				<el-table-column label="数量" prop="num" min-width="150" :show-overflow-tooltip="true" v-if="columns[7].visible" />
				<el-table-column label="状态" prop="inspectStatus" min-width="150" :show-overflow-tooltip="true" v-if="columns[8].visible">
					<template slot-scope="scope">
						<!-- <dict-tag :options="dict.type.inspect_status" :value="scope.row.inspectStatus" /> -->
            <el-tag type="warning"   v-if="scope.row.inspectStatus == '0' || scope.row.inspectStatus == '1'
            || scope.row.inspectStatus == '7'">{{ scope.row.inspectStatus == '0'?"待入库":scope.row.inspectStatus == '1'?'已入库':'待质检' }}</el-tag>
             <el-tag type="success"   v-if="scope.row.inspectStatus == '3' || scope.row.inspectStatus == '5'
            || scope.row.inspectStatus == '6'">{{ scope.row.inspectStatus == '3'?"合格":scope.row.inspectStatus == '5'?'让步接收':'已下发' }}</el-tag>
             <el-tag type="danger"   v-if="scope.row.inspectStatus == '2' || scope.row.inspectStatus == '4'">{{ scope.row.inspectStatus == '2'?"退货":'不合格' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" class-name="small-padding fixed-width" width="122px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildrens">
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)" v-hasPermi="['synthesize:sentrancelist:annex']">附件</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex2(scope.row)" v-hasPermi="['synthesize:sentrancelist:annex2']">附件</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<pagination menuNames="Pagination63" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
		<!-- 添加或修改发票对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" class="add-form1" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="接收人" prop="recipientId">
					<el-select v-model="form.recipientId" placeholder="请选择接收人" filterable @change="changeUser">
						<el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="接收日期" prop="recipientTime">
					<el-date-picker v-model="form.recipientTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择接收日期"> </el-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { listEntrancelist, listEntrancelistChild, delEntrancelist, submitIssue } from "@/api/synthesize/store/entrancelist"
import { mapGetters } from "vuex"
import { getUserList,getcolumn } from "@/api/selectList"
export default {
	name: "Entrancelist",
	dicts: ["default_approve", "product_intact_state", "inspect_status"],
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 设备保养计划表格数据
			EntrancelistList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				deviceName: undefined,
				inspectStatus: undefined,
				serialNumber: undefined,
				proposerName: undefined,
				inspectTime: undefined,
				deviceName: undefined,
				partNumber: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				recipientId: [{ required: true, message: "请选择接收人", trigger: "blur" }],
				recipientTime: [{ required: true, message: "请选择接收日期", trigger: "blur" }]
			},
			deviceList: [],
			// 更新树刷新
			treeMap: new Map(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 生产计划
			isOne: false,
			disabled: false,
			// 审批流程
			// openRecords: false,
			approveRecord: [],
			treetablekey: Math.random(),
			// 用户列表
			userList: [],
			// 列信息
			columns: [
				{ key: 0, label: `记录编号`, visible: true },
				{ key: 1, label: `申请单编号`, visible: true },
				{ key: 2, label: `申请人`, visible: true },
				{ key: 3, label: `供方`, visible: true },
				{ key: 4, label: `时间`, visible: true },
				{ key: 5, label: `产品名称`, visible: true },
				{ key: 6, label: `型号/图号`, visible: true },
				{ key: 7, label: `数量`, visible: true },
				{ key: 8, label: `状态`, visible: true }
			]
		}
	},
	created() {
		this.getSize()
		this.getUserList()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		this.getSize()
		this.getUserList()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
    getSize() {
			getcolumn({ pageName: "Pagination63" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
    	// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		// 获取用户下拉选
		getUserList() {
			getUserList().then(res => {
				this.userList = res.rows
			})
		},
		//
		changeUser() {
			let cur = this.userList.find(item => {
				return item.userId == this.form.recipientId
			})
			this.form.recipientName = cur.nickName
		},
		/** 查询设备保养计划列表 */
		getList() {
			this.loading = true
			listEntrancelist(this.queryParams).then(response => {
        response.rows.forEach((item, index) => {
					item.hasChildrens = true
					item.sort = index + 1
          this.$refs.table.toggleRowExpansion(item, false);
					item.children.forEach((items, indexs) => {
						items.sort = indexs + 1
            items.hasChildrens = false
            items.id = 'c'+items.id
					})
				})
				this.EntrancelistList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 获取列表详情
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, {
					treeNode,
					resolve
				})
			}
			let data = {
				id: tree.id,
				deviceName: this.queryParams.deviceName,
				inspectStatus: this.queryParams.inspectStatus,
				deviceName: this.queryParams.deviceName,
				partNumber: this.queryParams.partNumber
			}
			let ret = await listEntrancelistChild(data)
			ret.rows.forEach((item,index) => {
				// 父子id会冲突
				item.id = "c" + item.id
         item.sort = index+1
			})
			resolve(ret.rows)
		},
		// 取消按钮
		cancel() {
			this.$refs.table.clearSelection()
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				ids: undefined,
				recipientId: undefined,
				recipientName: undefined,
				recipientTime: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
			this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
				let flag = this.ids.some(item => item == row.id)
				if (row.hasChildrens) {
					row.children.forEach(items => {
						if (flag) {
							this.$refs.table.toggleRowSelection(items, true)
						}
					})
				}
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 提交下发 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					submitIssue(this.form).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.open = false
						this.$refs.table.clearSelection()
            this.getList()
						// this.refreshTree()
					})
				}
			})
		},
		// 附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 45,
					perm: "synthesize:sentrancelist:annex"
				}
			})
		},
		handleAnnex2(row) {
			let id = row.id.replace("c", "")
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: id,
					typeId: 46,
					perm: "synthesize:sentrancelist:annex2"
				}
			})
		},

		checkIds() {
			// 判断ids
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}
			let ids = this.ids.map(item => {
				return item.replace("c", "")
			})
			return ids
		},
		// 更新树
		refreshTree() {
			this.rows = []
			this.ids = []
			// 这个刷新checkbox有问题
			this.treeMap.forEach((item, idx) => {
				this.loadListDes({ id: idx }, item.treeNode, item.resolve)
			})
			// this.treetablekey = Math.random()
		},
		// 下发
		handleDown(row) {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			this.rows.forEach(item => {
				if (item.inspectStatus != "1" && item.inspectStatus != "3" && item.inspectStatus != "5") {
					checkrows = true
				}
			})
			if (checkrows) {
				this.$modal.msg("只有入库、合格、让步接收可以下发")
				return false
			}
			this.reset()
			this.form.ids = ids
			this.open = true
			this.title = "下发"
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 122px !important;
}
</style>
